package com.android.yinghebike.ui.fragment;

import android.graphics.Color;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.android.baselibrary.tool.Log;
import com.android.baselibrary.ui.BaseFragment;
import com.android.baselibrary.util.DateUtil;
import com.android.baselibrary.view.Comm_HeadView;
import com.android.yinghebike.R;
import com.android.yinghebike.bean.BleDataInfo;
import com.android.yinghebike.manager.BleManager;
import com.android.yinghebike.manager.UnitManager;
import com.android.yinghebike.ui.activity.Device_ListActivity;
import com.android.yinghebike.ui.view.Home_InfoView;
import com.gyf.immersionbar.ImmersionBar;

import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import cn.wandersnail.ble.Device;
import cn.wandersnail.ble.EasyBLE;
import cn.wandersnail.ble.EventObserver;
import cn.wandersnail.commons.util.StringUtils;

public class HomeMainFragment extends BaseFragment {

    @BindView(R.id.comm_title)
    Comm_HeadView comm_title;
    @BindView(R.id.tv_bluetooth_state)
    TextView tv_bluetooth_state;
    @BindView(R.id.tv_speed1)
    TextView tv_speed1;
    @BindView(R.id.tv_speed2)
    TextView tv_speed2;
    @BindView(R.id.tv_dangwei)
    TextView tv_dangwei;
    @BindView(R.id.pb_power)
    ProgressBar pb_power;
    @BindView(R.id.tv_power)
    TextView tv_power;
    @BindView(R.id.tv_gonglv)
    TextView tv_gonglv;
    @BindView(R.id.hi_speed_avg)
    Home_InfoView hi_speed_avg;
    @BindView(R.id.hi_time)
    Home_InfoView hi_time;
    @BindView(R.id.hi_distance)
    Home_InfoView hi_distance;
    @BindView(R.id.hi_total_distance)
    Home_InfoView hi_total_distance;
    @BindView(R.id.iv_bluetooth_state)
    ImageView iv_bluetooth_state;
    @BindView(R.id.tv_speed_unit)
    TextView tv_speed_unit;

    public static final byte Byte_Index_Speed = 0x00;     //实时速度相关起始index  主页的上半部分数据
    public static final byte Byte_Index_Mileage = 0x10;   //里程速度相关起始index，主页的下半部分数据

    List<BleDataInfo> dataInfoList_speed;
    List<BleDataInfo> dataInfoList_distance;
    Handler handler = new Handler();

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main;
    }

    @Override
    protected void initView() {
        comm_title.setTitle(getString(R.string.home_title));
        comm_title.setLeftImgVisible(View.GONE);

        ImmersionBar.with(this).statusBarDarkFont(false).titleBar(comm_title).navigationBarDarkIcon(false).init();
        EasyBLE.getInstance().registerObserver(eventObserver);

        checkBluetoothState();
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        try {
            if (mContext != null) {
                tv_speed_unit.setText(UnitManager.getSpeedUnitText());
                bindData1();
                bindData2();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onStart() {
        super.onStart();

    }


    @Override
    public void onPause() {
        super.onPause();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EasyBLE.getInstance().unregisterObserver(eventObserver);
    }

    //蓝牙事件
    EventObserver eventObserver = new EventObserver() {
        @Override
        public void onConnectionStateChanged(@NonNull Device device) {
            EventObserver.super.onConnectionStateChanged(device);
            switch (device.getConnectionState()) {
                case SCANNING_FOR_RECONNECTION:

                    break;
                case CONNECTING:
                    Log.i("连接中...");
                    break;
                case DISCONNECTED:
                    Log.i("连接断开");
                    checkBluetoothState();
//                    CommToast.showToast(mContext, "设备已断开");
                    break;
                case SERVICE_DISCOVERED:
                    Log.i("连接成功");
                    checkBluetoothState();
//                    CommToast.showToast(mContext, "设备已连接");
                    break;
            }
        }

        @Override
        public void onCharacteristicChanged(@NonNull Device device, @NonNull UUID service, @NonNull UUID characteristic, @NonNull byte[] value) {
            String hexStr = StringUtils.toHex(value, " ");
            Log.w("收到数据：" + hexStr);
            //5E 12 02 80 00 00 00 00 00 00 00 00 00 00 00 00 F2 0D
            //过滤掉不正常的数据，只取5E开头和0D结尾的数据
            if (value[0] == 0x5E && value[value.length - 1] == 0x0D) {
                List<BleDataInfo> dataInfoList = BleManager.getInstance().parseData(value);
                switch (value[3]) {
                    case Byte_Index_Speed:   //如果是速度开头的索引，就绑定上半部分的数据
                        dataInfoList_speed = dataInfoList;
                        bindData1();
                        break;
                    case Byte_Index_Mileage:  //如果是里程相关开头的索引，就绑定下半部分的数据
                        dataInfoList_distance = dataInfoList;
                        bindData2();
                        break;
                }
                handler.removeCallbacks(runnable);
                handler.postDelayed(runnable, 1000 * 3);
            }
        }
    };

    //根据蓝牙状态 显示不同图标，文字颜色
    private void checkBluetoothState() {
        if (BleManager.getInstance().isConnect()) {
            tv_bluetooth_state.setText(getString(R.string.comm_connected));
            tv_bluetooth_state.setTextColor(Color.WHITE);
            iv_bluetooth_state.setImageResource(R.drawable.ico_home_main_device_yilianjie);
        } else {
            tv_bluetooth_state.setText(getString(R.string.comm_unconnected));
            tv_bluetooth_state.setTextColor(Color.parseColor("#FD6D41"));
            iv_bluetooth_state.setImageResource(R.drawable.ico_home_main_device_weilianjie);
            //未连接，重置界面数据
            dataInfoList_speed = null;
            dataInfoList_distance = null;
            tv_speed1.setText("00.");
            tv_speed2.setText("0");
            tv_dangwei.setText("0");
            pb_power.setProgress(0);
            tv_power.setText(0 + "%");
            tv_gonglv.setText("000");

            hi_speed_avg.setContent(0 + " " + UnitManager.getSpeedUnitText());
            hi_distance.setContent(UnitManager.getDisplayDistanceByUnit(0));
            hi_total_distance.setContent(UnitManager.getDisplayDistanceByUnit(0));
            hi_time.setContent(DateUtil.generateTimeAll(0));
        }
    }

    //绑定实时速度相关
    private void bindData1() {
        try {
            if (dataInfoList_speed == null) return;
            //计算速度
            int dangwei = BleDataInfo.getDataByIndex(dataInfoList_speed, new byte[]{(byte) 0x01});
            int speed = BleDataInfo.getDataByIndex(dataInfoList_speed, new byte[]{(byte) 0x02, (byte) 0x03});
            int gonglv = BleDataInfo.getDataByIndex(dataInfoList_speed, new byte[]{(byte) 0x0a, (byte) 0x0b});
            int power = BleDataInfo.getDataByIndex(dataInfoList_speed, new byte[]{(byte) 0x06});

            String speedStr = (UnitManager.getDisplaySpeedByUnit(speed / 10d)) + "";
            Log.i("speed:"+ speed +   "  speedStr:"+ speedStr);
            tv_speed1.setText(speedStr.substring(0, 2));
            tv_speed2.setText(speedStr.substring(2));
            tv_dangwei.setText(dangwei + "");
            if(dangwei==15)
            {
                tv_dangwei.setText(  "P");  //挡位如果是15，显示P
            }
            pb_power.setProgress(power);
            tv_power.setText(power + "%");
            tv_gonglv.setText(gonglv + "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //绑定里程相关
    private void bindData2() {
        try {
            if (dataInfoList_distance == null) return;
            //平均速度
            int speedAvg = BleDataInfo.getDataByIndex(dataInfoList_distance, new byte[]{(byte) 0x1A, (byte) 0x1B});
            hi_speed_avg.setContent(UnitManager.getDisplaySpeedByUnit(speedAvg / 10d) + " " + UnitManager.getSpeedUnitText());
            //单次里程
            int distance = BleDataInfo.getDataByIndex(dataInfoList_distance, new byte[]{(byte) 0x10, (byte) 0x11, (byte) 0x12});
            hi_distance.setContent(UnitManager.getDisplayDistanceByUnit(distance));
            //总里程
            int total_distance = BleDataInfo.getDataByIndex(dataInfoList_distance, new byte[]{(byte) 0x13, (byte) 0x14, (byte) 0x15, (byte) 0x16});
            hi_total_distance.setContent(UnitManager.getDisplayDistanceByUnit(total_distance));
            //骑行时间
            int time = BleDataInfo.getDataByIndex(dataInfoList_distance, new byte[]{(byte) 0x17, (byte) 0x18, (byte) 0x19});
            Log.i("time:" + time);
            hi_time.setContent(DateUtil.generateTimeAll(time));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            BleManager.getInstance().disConnect();
        }
    };

    @OnClick({R.id.ll_device})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_device:    //点击设备连接
                StartActivity(Device_ListActivity.class);
                break;
        }
    }


}
